import datetime
import uuid

from django.shortcuts import redirect
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.authentication import JWTAuthentication

from apps.models import Order, User,OrderDetail
from apps.serializers.Order import OrderSerializer, OrderDetailSerializer
from apps.serializers.OrderPay import OrderPaySerializer
from apps.utils.common_function import log_error
from apps.utils.common_mixin import APICreateModelMixin
from apps.utils.common_response import APIResponse


class OrderListView(GenericViewSet):
    def list(self, request):
        userId = request.GET.get('userId')
        orderStatus = request.GET.get('orderStatus')
        orders = Order.objects.all().filter(user=userId).filter(status__contains=orderStatus).order_by('-order_time')
        serializer = OrderSerializer(orders, many=True)
        return APIResponse(code=0, msg='查询成功', data=serializer.data)
class OrdeRetriveView(GenericViewSet):
    def list(self, request):
        userId = request.GET.get('userId')
        orderStatus = request.GET.get('orderStatus')
        orders = Order.objects.all().filter(user=userId).filter(status__contains=orderStatus).order_by('-order_time')
        serializer = OrderSerializer(orders, many=True)
        return APIResponse(code=0, msg='查询成功', data=serializer.data)

class CreateOrderView(GenericViewSet,APICreateModelMixin):
    queryset = OrderDetail.objects.all()
    serializer_class = OrderDetailSerializer



class OrderPayView(GenericViewSet):
    # 必须登录才能访问：认证类  权限类
    authentication_classes = []
    permission_classes = []
    # 校验--》生成支付链接--》生成订单--》序列化类的validate中
    serializer_class = OrderPaySerializer

    def create(self, request, *args, **kwargs):
        # print(request.data)
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()  # 下单-》生成订单,--》重写create方法
        pay_url = serializer.context.get('pay_url')
        redirect('www.baidu.com')
        return APIResponse(pay_url=pay_url)


class OrderSuccessView(GenericViewSet):
    def list(self, request):
        # 给咱们前端用
        # 1 取出订单号
        out_trade_no = request.GET.get('out_trade_no')
        if out_trade_no:  # 说明支付宝的post回调回来了，修改了订单状态
            order = Order.objects.filter(out_trade_no=out_trade_no, status=2).first()
            data = request.data
            data['status'] = 4
            serializer = OrderSerializer(order, data=request.data)
            #检验保存
            if serializer.is_valid():
                serializer.save()
            return APIResponse(msg='支付成功，欢迎下次光临',data=serializer.data)
        else:
            return APIResponse(code=101, msg='暂未收到您的付款，请稍后刷新再试')

class OrderCancel(GenericViewSet):
    def create(self,request):
        try:
            pk = request.GET.get('id', -1)
            order = Order.objects.get(pk=pk)
        except Order.DoesNotExist:
            return APIResponse(code=1, msg='对象不存在')
        data = {
            'status': 4
        }
        serializer = OrderSerializer(order, data=data)
        if serializer.is_valid():
            serializer.save()
            # 加库存
            # thingId = request.data['thing']
            # thing = Thing.objects.get(pk=thingId)
            # thing.repertory = thing.repertory + 1
            # thing.save()

            # 加积分
            # order.user.score = order.user.score + 1
            # order.user.save()

            return APIResponse(code=0, msg='取消成功', data=serializer.data)
        else:
            print(serializer.errors)
            return APIResponse(code=1, msg='更新失败')